﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace PowerPointWebController
{
    public partial class MainForm : Form
    {
        Listener listener = null;
        private delegate void updateTextBox(string value);

        public MainForm()
        {
            InitializeComponent();
            txtPort.Text = "" + 9999;
        }

        private void Close(object sender, FormClosingEventArgs e)
        {
            if (listener != null)
                listener.stop();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (txtPort.Text == null || txtPort.Text.Length == 0)
            {
                MessageBox.Show("Must enter a port number.");
                return;
            }

            int port = 0;
            if (!int.TryParse(txtPort.Text.Trim(), out port))
            {
                MessageBox.Show("Port number must be a number.");
                return;
            }
            txtPort.Enabled = false;
            btnStart.Enabled = false;
            listener = new Listener();
            listener.IPAddressNotify += new Listener.RaiseIPAddressNotify_delegate(listener_IPAddressNotify);
            listener.start(port);
        }

        private void updatePortText(string value)
        {
            if (value != null)
            {
                txtPort.Text = value;
            }
        }

        void listener_IPAddressNotify(System.Net.IPAddress ip)
        {
            //Update the port text box with the ip address that
            //is being used to listen on.  Is done in a different
            //thread and therefore needs to use Invoke method
            txtPort.Invoke(new updateTextBox(updatePortText), new object[] {ip.ToString()+":"+txtPort.Text});
        }

    }
}
